extends Node2D
class_name GameManager

# 游戏状态
enum GameState {
	PLAYING,
	PAUSED,
	GAME_OVER,
	VICTORY
}

# 游戏变量
var game_state: GameState = GameState.PLAYING
var score: int = 0
var lives: int = 3
var current_level: int = 1
var enemy_count: int = 0
var max_enemies: int = 20

# 场景引用
@onready var player_container = $GameArea/Player
@onready var enemies_container = $GameArea/Enemies
@onready var bullets_container = $GameArea/Bullets
@onready var walls_container = $GameArea/Walls
@onready var rewards_container = $GameArea/Rewards
@onready var explosions_container = $GameArea/Explosions

# UI引用
@onready var score_label = $UI/GameUI/ScoreLabel
@onready var lives_label = $UI/GameUI/LivesLabel
@onready var level_label = $UI/GameUI/LevelLabel
@onready var game_over_screen = $UI/GameUI/GameOverScreen
@onready var restart_button = $UI/GameUI/GameOverScreen/GameOverPanel/RestartButton

# 音效
@onready var audio_player = AudioStreamPlayer.new()
var audio_manager: AudioManager

# 预加载场景
var player_scene = preload("res://scenes/Player.tscn")
var enemy_scene = preload("res://scenes/EnemyTank.tscn")
var bullet_scene = preload("res://scenes/Bullet.tscn")
var explosion_scene = preload("res://scenes/Explosion.tscn")
var reward_scene = preload("res://scenes/Reward.tscn")

# 预加载音效 - 暂时注释掉有问题的音效
# var shoot_sound = preload("res://assets/Sounds/shoot.wav")
# var explosion_sound = preload("res://assets/Sounds/kill.wav")
# var background_music = preload("res://assets/Sounds/background.mp3")

func _ready():
	# 添加音频播放器
	add_child(audio_player)
	
	# 创建音频管理器
	audio_manager = AudioManager.new()
	add_child(audio_manager)
	
	# 连接按钮信号
	restart_button.pressed.connect(_on_restart_button_pressed)
	
	# 开始游戏
	start_game()

func start_game():
	# 重置游戏状态
	game_state = GameState.PLAYING
	score = 0
	lives = 3
	current_level = 1
	enemy_count = 0
	
	# 更新UI
	update_ui()
	
	# 播放背景音乐 - 暂时禁用
	# play_background_music()
	
	# 创建玩家
	create_player()
	
	# 创建地图
	create_level()
	
	# 开始生成敌人
	start_enemy_spawning()

func create_player():
	# 清除现有玩家
	for child in player_container.get_children():
		child.queue_free()
	
	# 创建新玩家
	var player = player_scene.instantiate()
	player.position = Vector2(400, 500)  # 玩家起始位置
	player_container.add_child(player)
	
	# 连接玩家信号
	player.player_died.connect(_on_player_died)
	player.player_shot.connect(_on_player_shot)

func create_level():
	# 清除现有地图元素
	for child in walls_container.get_children():
		child.queue_free()
	
	# 创建边界墙
	create_boundary_walls()
	
	# 创建内部障碍物
	create_internal_walls()

func create_boundary_walls():
	# 创建边界墙
	var wall_texture = preload("res://assets/Images/Wall/StoneWall.png")
	
	# 上边界
	for i in range(0, 800, 25):
		create_wall(Vector2(i, 0), wall_texture)
	
	# 下边界
	for i in range(0, 800, 25):
		create_wall(Vector2(i, 600), wall_texture)
	
	# 左边界
	for i in range(0, 600, 25):
		create_wall(Vector2(0, i), wall_texture)
	
	# 右边界
	for i in range(0, 600, 25):
		create_wall(Vector2(775, i), wall_texture)

func create_internal_walls():
	# 创建内部砖墙障碍物
	var brick_texture = preload("res://assets/Images/Wall/BrickWall.png")
	
	# 创建一些砖墙障碍物
	var wall_positions = [
		Vector2(200, 200), Vector2(225, 200), Vector2(250, 200),
		Vector2(500, 300), Vector2(525, 300), Vector2(550, 300),
		Vector2(300, 400), Vector2(325, 400), Vector2(350, 400),
		Vector2(600, 150), Vector2(625, 150), Vector2(650, 150)
	]
	
	for pos in wall_positions:
		create_wall(pos, brick_texture)

func create_wall(pos: Vector2, texture: Texture2D):
	var wall = StaticBody2D.new()
	var collision = CollisionShape2D.new()
	var sprite = Sprite2D.new()
	
	# 设置精灵
	sprite.texture = texture
	sprite.position = Vector2(12.5, 12.5)  # 居中
	
	# 设置碰撞
	var shape = RectangleShape2D.new()
	shape.size = Vector2(25, 25)
	collision.shape = shape
	
	# 添加到场景
	wall.add_child(sprite)
	wall.add_child(collision)
	wall.position = pos
	walls_container.add_child(wall)
	
	# 添加Area2D用于子弹碰撞检测
	var area = Area2D.new()
	var area_collision = CollisionShape2D.new()
	area_collision.shape = shape
	area.add_child(area_collision)
	wall.add_child(area)

func start_enemy_spawning():
	# 开始生成敌人
	var timer = Timer.new()
	timer.wait_time = 3.0  # 每3秒生成一个敌人
	timer.timeout.connect(_spawn_enemy)
	timer.autostart = true
	add_child(timer)

func _spawn_enemy():
	if enemy_count >= max_enemies or game_state != GameState.PLAYING:
		return
	
	# 随机选择生成位置
	var spawn_positions = [
		Vector2(50, 50),   # 左上
		Vector2(700, 50),  # 右上
		Vector2(50, 550),  # 左下
		Vector2(700, 550)  # 右下
	]
	
	var spawn_pos = spawn_positions[randi() % spawn_positions.size()]
	
	# 创建敌人
	var enemy = enemy_scene.instantiate()
	enemy.position = spawn_pos
	enemies_container.add_child(enemy)
	
	# 连接敌人信号
	enemy.enemy_died.connect(_on_enemy_died)
	enemy.enemy_shot.connect(_on_enemy_shot)
	
	enemy_count += 1

func _on_player_died():
	lives -= 1
	update_ui()
	
	if lives <= 0:
		game_over()
	else:
		# 重新创建玩家
		await get_tree().create_timer(1.0).timeout
		create_player()

func _on_enemy_died(enemy_score: int):
	score += enemy_score
	enemy_count -= 1
	update_ui()
	
	# 播放爆炸音效 - 使用简单音效
	if audio_manager:
		audio_manager.play_explosion_sound()
	
	# 检查是否胜利
	if enemy_count <= 0:
		next_level()

func _on_player_shot(bullet_pos: Vector2, direction: Vector2):
	create_bullet(bullet_pos, direction, true)

func _on_enemy_shot(bullet_pos: Vector2, direction: Vector2):
	create_bullet(bullet_pos, direction, false)

func create_bullet(pos: Vector2, direction: Vector2, is_player_bullet: bool):
	var bullet = bullet_scene.instantiate()
	bullet.position = pos
	bullet.direction = direction
	bullet.is_player_bullet = is_player_bullet
	bullets_container.add_child(bullet)
	
	# 连接子弹信号
	bullet.bullet_hit.connect(_on_bullet_hit)
	
	# 播放射击音效 - 使用简单音效
	if audio_manager:
		audio_manager.play_shoot_sound()

func _on_bullet_hit(hit_pos: Vector2, _is_player_bullet: bool):
	# 创建爆炸效果
	create_explosion(hit_pos)

func create_explosion(pos: Vector2):
	var explosion = explosion_scene.instantiate()
	explosion.position = pos
	explosions_container.add_child(explosion)

func next_level():
	current_level += 1
	max_enemies += 5  # 每关增加敌人数量
	
	# 清除所有敌人
	for child in enemies_container.get_children():
		child.queue_free()
	
	enemy_count = 0
	
	# 重新创建地图
	create_level()
	
	# 更新UI
	update_ui()
	
	# 开始新关卡
	start_enemy_spawning()

func game_over():
	game_state = GameState.GAME_OVER
	game_over_screen.visible = true

func _on_restart_button_pressed():
	game_over_screen.visible = false
	start_game()

func update_ui():
	score_label.text = "分数: " + str(score)
	lives_label.text = "生命: " + str(lives)
	level_label.text = "关卡: " + str(current_level)

func play_sound(sound: AudioStream):
	audio_player.stream = sound
	audio_player.play()

func play_background_music():
	# 暂时禁用背景音乐
	# audio_player.stream = background_music
	# audio_player.volume_db = -10  # 降低背景音乐音量
	# audio_player.play()
	pass
